import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterstart/widgets/img_crop.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';

class ImgUpload extends StatefulWidget {
  ImgUpload(
      {Key key,
      this.defaultFiles: const [],
      this.onChanged,
      this.height,
      this.width,
      this.max: 10,
      this.tip})
      : super(key: key);

  /// 默认展示的图片
  final List<String> defaultFiles;

  /// 改变事件
  final ValueChanged<List<File>> onChanged;

  /// 高度
  final double height;

  /// 宽度
  final double width;

  /// 图片的最大张数
  final int max;

  /// 添加的图片的提示中文
  final String tip;

  @override
  _ImgUpload createState() => _ImgUpload();
}

class _ImgUpload extends State<ImgUpload> {
  /// 图片对象列表（未上传）
  List<File> _fileList = [];

  /// 错误信息
  String _pickImageError;

  /// 恢复数据的错误
  String _retrieveDataError;

  /// 缩略图高和宽
  double displayHeight = 90;
  double displayWidth = 90;

  /// 裁剪图片
  void _cropImage(File originalImage) async {
    Navigator.pop(context);
    dynamic result = await Navigator.push(context,
        MaterialPageRoute(builder: (context) => ImgCrop(originalImage)));
    if (result is String) {
      Fluttertoast.showToast(msg: result, gravity: ToastGravity.BOTTOM);
    } else {
      setState(() {
        _fileList.add(result);
      });
    }
  }

  /// 选择照片
  void _onImageButtonPressed(ImageSource source, {BuildContext context}) async {
    try {
      File file = await ImagePicker.pickImage(source: source, imageQuality: 8);
      if (file != null) {
        Timer(Duration(milliseconds: 200), () {
          _cropImage(file);
        });
      }
    } catch (e) {
      _pickImageError = e.toString();
      Fluttertoast.showToast(msg: '选择图片失败', gravity: ToastGravity.BOTTOM);
    }
  }

  /// 添加图片选项
  Widget _getImgOption(type, text) {
    /// 按钮样式
    EdgeInsetsGeometry padding = EdgeInsets.symmetric(vertical: 14);

    /// 文字样式
    TextStyle textStyle = TextStyle(color: Colors.black, fontSize: 14);
    return GestureDetector(
      key: UniqueKey(),
      onTap: () {
        Navigator.pop(context);
        if (type == 'camera') {
          _onImageButtonPressed(ImageSource.camera, context: context);
        } else if (type == 'gallery') {
          _onImageButtonPressed(ImageSource.gallery, context: context);
        } else {}
      },
      child: Container(
        color: Colors.red,
        width: double.infinity,
        padding: padding,
        alignment: Alignment.center,
        height: 42,
        child: Text(
          text,
          style: textStyle,
        ),
      ),
    );
  }

  /// 添加图片部件
  Widget _getAddWidget(context) {
    Widget addIcon = Icon(
      Icons.add,
      color: Color(0xff999999),
      size: 50,
    );
    return Container(
      margin: EdgeInsets.only(right: 6, bottom: 6),
      constraints: BoxConstraints(
          maxHeight: displayHeight,
          maxWidth: displayWidth,
          minWidth: displayWidth,
          minHeight: displayHeight),
      decoration: BoxDecoration(
        color: Color(0xffF5F5F5),
        borderRadius: BorderRadius.all(Radius.circular(10)),
      ),
      child: Center(
          child: GestureDetector(
        onTap: () {
          showModalBottomSheet(
              isDismissible: false,
              shape: const RoundedRectangleBorder(
                  side: BorderSide.none,
                  borderRadius:
                      BorderRadius.vertical(top: Radius.circular(14))),
              context: context,
              clipBehavior: Clip.hardEdge,
              builder: (BuildContext context) {
                return SizedBox(
                    height: 140,
                    child: Column(
                      children: <Widget>[
                        _getImgOption('camera', '拍照'),
                        Divider(
                          thickness: 1,
                          color: Color(0xffaaaaaa),
                          height: 4,
                        ),
                        _getImgOption('gallery', '从手机相册选择'),
                        Divider(
                          thickness: 10,
                          color: Color.fromRGBO(90, 90, 90, 0.6),
                          height: 10,
                        ),
                        _getImgOption('cacel', '取消'),
                      ],
                    ));
              });
        },
        child: widget.tip == null
            ? addIcon
            : Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  addIcon,
                  Padding(
                    padding: EdgeInsets.only(top: 6),
                    child: Text(
                      widget.tip,
                      style: TextStyle(fontSize: 14),
                    ),
                  )
                ],
              ),
      )),
    );
  }

  /// 图片显示
  Widget _getImg(url, isFile) {
    return Container(
      margin: EdgeInsets.only(right: 6, bottom: 6),
      width: displayWidth,
      height: displayHeight,
      decoration: BoxDecoration(
        color: Color(0xffF5F5F5),
        borderRadius: BorderRadius.all(Radius.circular(10)),
        image:
            DecorationImage(image: isFile ? FileImage(url) : NetworkImage(url)),
      ),
    );
  }

  /// 图片预览
  Widget _previewImage(context) {
    final bool retrieveError = _isRetrieveError();
    if (retrieveError) {
      return null;
    }
    List<Widget> list = [];

    /// 添加默认显示的图片
    widget.defaultFiles.forEach((url) {
      list.add(_getImg(url, false));
    });

    /// 添加从相册或者相机选择的图片
    _fileList.forEach((file) {
      list.add(_getImg(file, true));
    });

    /// 如果还可以添加，就加入添加组件
    if (list.length < widget.max) {
      list.add(_getAddWidget(context));
    }

    return Wrap(
      children: list,
    );
  }

  bool _isRetrieveError() {
    if (_retrieveDataError != null) {
      Fluttertoast.showToast(msg: '图片加载失败，请重试');
      _retrieveDataError = null;
      return true;
    }
    return false;
  }

  /// 安卓恢复数据
  Future<void> retrieveLostData() async {
    final LostDataResponse response = await ImagePicker.retrieveLostData();
    if (response.isEmpty) {
      return;
    }
    if (response.file != null) {
      setState(() {
        _fileList.removeLast();
        _fileList.add(response.file);
      });
    } else {
      _retrieveDataError = response.exception.code;
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.height == null) {
      MediaQueryData mediaQuery = MediaQueryData.fromWindow(ui.window);
      displayHeight = (mediaQuery.size.width - 80) / 3;
      displayWidth = (mediaQuery.size.width - 80) / 3;
    } else {
      displayHeight = widget.height;
      displayWidth = widget.width;
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () async {},
        child: Container(
          alignment: Alignment.centerLeft,
          child: Wrap(
            children: <Widget>[
              Platform.isAndroid
                  ? FutureBuilder<void>(
                      future: retrieveLostData(),
                      builder:
                          (BuildContext context, AsyncSnapshot<void> snapshot) {
                        return _previewImage(context);
                      })
                  : _previewImage(context)
            ],
          ),
        ));
  }
}
